const http = require('http');
const fs = require('fs');
const querystring = require('querystring');
const urlLib = require('url');
var users = {};// 临时保存用户名  不会被请求重置
var server = http.createServer(function (req, res) {
    //解析url
    var obj = urlLib.parse(req.url, true);
    var url = obj.pathname;
    //获取get请求数据
    var GET = obj.query;
    var str = '';
    
    //获取post请求数据
    req.on('data', function (data) {
        str += data;
    });

    req.on('end', function () {
        //解析post请求数据
        var POST = querystring.parse(str);
        console.log( url, GET, POST );
        //区分接口和文件访问
        if (url == '/user') {
            switch (GET.act) {
                case 'reg'://注册
                    if( POST.user == "" || POST.user==null )
                    {
                        res.write('{"status":"false","msg":"用户名不能为空"}');
                        break;
                    }
                    if( POST.pwd == "" || POST.pwd==null )
                    {
                        res.write('{"status":"false","msg":"密码不能为空"}');
                        break;
                    }
                    
                    if (users[POST.user]) {
                        res.write('{"status":"false","msg":"用户名重复"}');
                    } else {
                        users[POST.user] = POST.pwd;
                        res.write('{"status":"ture","msg":"注册成功"}');
                    }
                    break;
                case 'login':
                    if (users[POST.user]) {
                        //校验密码
                        if (users[POST.user] != POST.pwd) {
                            res.write('{"status":"false","msg":"密码错误"}');
                        } else {
                            res.write('{"status":"true","msg":"登录成功"}');
                        }
                    } else {
                        res.write('{"status":"false","msg":"用户名错误"}');
                    }
                    break;
                default:
                    res.write('{"status":"false","msg":"未知操作"}');
            }
            console.log( users );
            res.end();
        } else {
            //解析请求文件
            var file_name = './www' + url;

            if (url == '/') {
                //默认访问www/index.html
                file_name = './www/index.html';
            }

            fs.readFile(file_name, function (err, data) {
                if (err) {
                    res.write('404');
                } else {
                    res.write(data);
                }
                res.end();
            });
        }
    });
});

server.listen(8080);
